<?php

namespace App\Http\Controllers\Api\Repositories;


use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Models\WxSyncRelation;
use App\Models\User\WxUser as Model;
use App\Models\User\WxUserFollow;
use App\Models\User\WxUserTemp;
use App\Wen\Utils\UserUtils;
use Illuminate\Support\Facades\Cache;


class WxUserRepositores
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;



    /**
     * @return mixed
     */
    public function info($uid)
    {
        return (new $this->eloquentClass())->where('id', $uid)->where('user_state', '<>', 1)->first(FieldUtils::userInfoColums());
    }

    private static function _update_openid($user, $open_id, $mp_openid, $web_openid, $app_openid, $shop_openid, $union_id = null){

        if($open_id || $mp_openid || $web_openid || $app_openid || $shop_openid){
            $updates = [];
            if($open_id){
                $updates['weixin_openid'] = $open_id;
            }
            if($mp_openid){
                $updates['weixin_mp_openid'] = $mp_openid;
            }
            if($web_openid){
                $updates['weixin_web_openid'] = $web_openid;
            }
            if($app_openid){
                $updates['weixin_app_openid'] = $app_openid;
            }
            if($shop_openid){
                $updates['weixin_shop_openid'] = $shop_openid;
            }
            if($union_id){
                $updates['weixin_unionid'] = $union_id;
            }
            WxUser::where('id', $user['id'])->update($updates);
        }
    }

    /** collectUserData()
     * @param $data [ mp_openId,web_openId,app_openId,unionId,nickName,user_background_maps,avatarUrl,gender,id=>external_id,date ]
     * @return bool
     */
    public static function registerUser($data)
    {
        $uid = WxSyncRelationRepositories::wx_uid($data['domain'], $data['external_id']);
        if($uid){
            return $uid;
        }

        $mp_openId = $data['mp_openId'];
        if(_empty_($mp_openId)){
            $mp_openId = null;
        }
        $web_openId = $data['web_openId'] ?: null;
        if(_empty_($web_openId)){
            $web_openId = null;
        }
        $app_openId = $data['app_openId'] ?: null;
        if(_empty_($app_openId)){
            $app_openId = null;
        }

        $unionId = $data['unionId'] ?: null;
        if(_empty_($unionId)){
            $unionId = null;
        }

        if($unionId){
            // 判断是否已经注册过
            $uid_user = WxUser::where('weixin_unionid',$unionId)->first();
            if($uid_user){
                self::_update_openid($uid_user, null, $mp_openId, $web_openId, $app_openId, null);
                return $uid_user->id;
            }
        }else{
            // 判断是否已经注册过
            if($mp_openId || $web_openId || $app_openId){
                if($mp_openId){
                    $openid_user = WxUser::where('weixin_mp_openid',$mp_openId)->first();
                    if($openid_user){
                        self::_update_openid($openid_user, null, null, $web_openId, $app_openId, null, $unionId);
                        return $openid_user->id;
                    }
                }else if($web_openId){
                    $openid_user = WxUser::where('weixin_web_openid',$web_openId)->first();
                    if($openid_user){
                        self::_update_openid($openid_user, null, $mp_openId, null, $app_openId, null, $unionId);
                        return $openid_user->id;
                    }
                }else if($app_openId){
                    $openid_user = WxUser::where('weixin_app_openid',$app_openId)->first();
                    if($openid_user){
                        self::_update_openid($openid_user, null, $mp_openId, $web_openId, null, null, $unionId);
                        return $openid_user->id;
                    }
                }
            }
        }
        while (Model::where('user_name',$data['nickName'])->exists()){
            $data['nickName'] .= '_'.mt_rand(1, 100);
        }
//        $maxId = WxUser::max('id');
        $user = new Model();
        $user->weixin_openid = null;
        $user->weixin_app_openid=$app_openId;
        $user->weixin_mp_openid=$mp_openId;
        $user->weixin_web_openid=$web_openId;
        $user->weixin_shop_openid=null;

        $user->weixin_unionid=$unionId;
        $user->user_name=$data['nickName'];
        $user->weixin_name=$data['nickName'];
        $user->user_background_maps = _array_key($data, 'user_background_maps', Settings::get('user_background_maps'));
        $user->user_avatar= _array_key($data, 'avatarUrl', Settings::get('img_default'));
        $user->country=$data['country'] ?? '';
        $user->province=$data['province'] ?? '';
        $user->city=$data['city'] ?? '';
        // [0 => '未知',1 => '男',2 => '女']
        $user->gender=$data['gender'] ?? 0;
        if($data['date']){
            $user->updated_at =  strtotime($data['date']);
            $user->created_at = strtotime($data['date']);
        }
        $user->save();
        $uid = $user->id;

        if($data['external_id'] && $data['domain']){
            $sync = new WxSyncRelation();
            $sync->domain = $data['domain'];
            $sync->type = 'user';
            $sync->inner_id = $uid;
            $sync->external_id = $data['external_id'];
            $sync->status = 1;
            $sync->save();
        }

        return $user->id;
    }

    /**
     * 更新
     * @param $uid
     * @param $data
     * @return mixed
     */
    public static function update($uid, $data, $need_manual_review)
    {
        $data['user_name'] = str_replace([' 🤖', '🤖',' 💙🤖', ' 💗🤖', '💙🤖', '💗🤖'], '', trim(_array_key($data, 'user_name', '')));
        while ( WxUser::where([['user_name','=',$data['user_name']], ['id', '<>', $uid] ])->exists() ){
            $data['user_name'] .= '_'.mt_rand(1, 100);
        }
        // 先更新标签
        if(_array_key($data, 'user_labels', [])){
            if(_array_key($data, 'user_labels', []) == -1){
                update_user_meta($uid, 'user_labels', null, 'j');
            }else{
                update_user_meta($uid, 'user_labels', _array_key($data, 'user_labels', []), 'j');
            }
        }

        // 判断是否需要审核用户的资料
        if (!$need_manual_review) {
            $update_arr = [];
            if(!_empty_(_array_key($data, 'user_avatar', ''))){
                $update_arr['user_avatar'] = _array_key($data, 'user_avatar', '');
            }
            if(!_empty_(_array_key($data, 'user_name', ''))){
                $update_arr['user_name'] = _array_key($data, 'user_name', '');
            }
            if(!_empty_(_array_key($data, 'user_introduce', ''))){
                $update_arr['user_introduce'] = _array_key($data, 'user_introduce', '');
            }
            if(!_empty_(_array_key($data, 'user_birthday', ''))){
                $update_arr['user_birthday'] = _array_key($data, 'user_birthday', '');
            }
            if(!_empty_(_array_key($data, 'user_background_maps', ''))){
                $update_arr['user_background_maps'] = _array_key($data, 'user_background_maps', '');
            }

            if(!_empty_(_array_key($data, 'wechat_account', ''))){
                $update_arr['wechat_account'] = _array_key($data, 'wechat_account', '');
            }

            if(!_empty_(_array_key($data, 'gender', 0), true)){
                $update_arr['gender'] = _array_key($data, 'gender', 0);
            }

            $r = WxUser::where('id', $uid)->update($update_arr);
            if($update_arr){
                if($r && !$need_manual_review){
                    UserUtils::assistant_notice($uid,  '您提交的资料审核通过，已经为您更新。');
                    GatewayUtils::success(GatewayUtils::uid2client_id($uid), 12);
                }
                return $r;
            }
            return false;
        } else {

            if(!_empty_(_array_key($data, 'wechat_account', ''))){
                WxUser::where('id', $uid)->update(['wechat_account'=>_array_key($data, 'wechat_account', '')]);
            }

            if(WxUserTemp::where([['user_id', '=', $uid], ['user_state', '=', 0]])->exists()){
                $update_arr = [];
                if(!_empty_(_array_key($data, 'user_avatar', ''))){
                    $update_arr['user_avatar'] = _array_key($data, 'user_avatar', '');
                }
                if(!_empty_(_array_key($data, 'user_name', ''))){
                    $update_arr['user_name'] = _array_key($data, 'user_name', '');
                }
                if(!_empty_(_array_key($data, 'user_introduce', ''))){
                    $update_arr['user_introduce'] = _array_key($data, 'user_introduce', '');
                }
                if(!_empty_(_array_key($data, 'user_birthday', ''))){
                    $update_arr['user_birthday'] = _array_key($data, 'user_birthday', '');
                }
                if(!_empty_(_array_key($data, 'user_background_maps', ''))){
                    $update_arr['user_background_maps'] = _array_key($data, 'user_background_maps', '');
                }

                if(!_empty_(_array_key($data, 'gender', 0), true)){
                    $update_arr['gender'] = _array_key($data, 'gender', 0);
                }
                if($update_arr){
                    $r = WxUserTemp::where('user_id', $uid)->update($update_arr);
                    return $r;
                }
                return false;
            }else{
                // 先驳回之前的资料申请
                if(WxUserTemp::where( [ ['user_id','=', $uid], ['user_state', '=', 0] ] )->exists()){
                    WxUserTemp::where( [ ['user_id','=', $uid], ['user_state', '=', 0] ] )->update(['user_state'=>2]);
                }
                $UserTempModel = new WxUserTemp();
                $UserTempModel->user_id = $uid;
                $UserTempModel->user_avatar = _array_key($data, 'user_avatar', '');
                $UserTempModel->user_name = _array_key($data, 'user_name', '');
                $UserTempModel->user_introduce = _array_key($data, 'user_introduce', '');
                $UserTempModel->user_birthday = _array_key($data, 'user_birthday', '');
                $UserTempModel->user_background_maps = _array_key($data, 'user_background_maps', '');
                $UserTempModel->gender = _array_key($data, 'gender', 0);
                return $UserTempModel->save();
            }
        }
    }

    /**
     * @param $keyword
     * @param int $uid
     * @param int $limit
     */
    public static function searchUser($keyword, $uid = 0, $limit = 10, $is_record = true, $is_tenant = false)
    {
        if($is_record){
            WxSearchRepositores::record($uid, $keyword);
        }
        global $__MINI_GLOBAL_TENANT_ID__;
        $query = (new Model())->where(function ($q) use ($keyword) {
//          $keyword = base64_encode($keyword);
            $q->where('user_name', 'like', '%' . $keyword . '%')->orWhere('id', $keyword);
        });
        if($is_tenant){
            $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);
        }
        $data = $query->simplePaginate($limit, FieldUtils::userInfoColums());
        $data->map(function ($v) use ($uid) {
            $v->is_follow_user = (new WxUserFollow())->isFollowUser($uid, $v->id);
        });
        return $data;
    }

    /**
     * 订单状态
     * @param $type
     */
    public static function orderType($type)
    {
        $data = [];
        switch ($type) {
            case 1:
                $data['title'] = '会员订单';
                $data['details'] = '开通'.Settings::get('app_title').'大会员';
                break;
            case 2:
                $data['title'] = '充电订单';
                $data['details'] = '充电了一篇你感兴趣的笔记';
                break;
            case 3:
                $data['title'] = '充值订单';
                $data['details'] = '您进行了余额充值';
                break;
            case 4:
                $data['title'] = '购买付费贴';
                $data['details'] = '';
                break;
            case 6:
                $data['title'] = '笔记推广';
                $data['details'] = '';
                break;
            case 7:
                $data['title'] = '加入付费圈子';
                $data['details'] = '';
                break;
            case 8:
                $data['title'] = '保证金充值';
                $data['details'] = '';
                break;
            case 9:
                $data['title'] = '购买迷你模块';
                $data['details'] = '';
                break;
            case 10:
                $data['title'] = '解除账号限制';
                $data['details'] = '';
                break;
            case 11:
                $data['title'] = '付费获取Ta人联系方式';
                $data['details'] = '';
                break;
        }
        return $data;
    }

    /**
     * 提现记录状态
     * @param $type
     */
    public static function withdrawalType($type)
    {
        $title = '';
        switch ($type) {
            case 0:
                $title = '受理中';
                break;
            case 1:
                $title = '已到账';
                break;
            case 2:
                $title = '提现异常，请联系客服处理';
                break;
            case 3:
                $title = '微信打款中';
                break;
            case 4:
                $title = '支付宝打款中';
                break;
        }
        return $title;
    }

    /**
     * [ openId,unionId,nickName,avatarUrl,gender,date ]
     * @param $uid
     * @return array
     */
    public static function userData($uid)
    {
        $user = WxUser::where('id', $uid)->first();
        if(_empty_($user)){
            return [];
        }
        // $name, $open_id, $avater, $gender, $date
        // [0 => '未知',1 => '男',2 => '女']
        return ['nickName'=>$user->user_name, 'mp_openId'=>$user->weixin_mp_openid,'app_openId'=>$user->weixin_app_openid,'web_openId'=>$user->weixin_web_openid,
            'unionId'=>$user->weixin_unionid ?: '', 'avatarUrl'=>$user->user_avatar, 'gender'=>$user->gender, 'date'=>$user->created_at->toDateTimeString()];
    }

    public static function isOfficial($uid){
        return WxUser::where('id', $uid)->value('is_official');
    }

    /**
     * 开通会员
     * @param $uid
     */
    public static function vip($uid, $days = 1)
    {
        global $__MINI_GLOBAL_PAYCODE_16__;
        if(!$__MINI_GLOBAL_PAYCODE_16__){
            return;
        }
        $is_renew = false;
        $member_time = _get_origin_attribute('wx_user', [['id', '=', $uid]], 'is_member');
        if($member_time){
            $member_time = (int)$member_time;
            if($member_time <= time()){
                // 过期了
                $member_time = time();
            }else{
                $is_renew = true;
            }
        }else{
            $member_time = time();
        }
        // 增加天数
        $member_time += 3600 * 24 * $days;
        WxUser::where('id', $uid)->update(['is_member' => (string)$member_time ]);
        if($is_renew){
            UserUtils::add_user_notice(4002, $uid, '续费会员', '您已成功续费'.$days.'天会员服务', 100);
        }else{
            UserUtils::add_user_notice(4003, $uid, '开通会员', '您已成功开通'.$days.'天会员服务', 100);
        }
        Cache::forget('get:cached:user:'.$uid);

    }

}
